import html2canvas from 'html2canvas';
import jsPDF from 'jspdf'

// export const htmlToPDF = async (htmlId: string, title: string = "报表", bgColor = "#fff") => {
// 	let pdfDom: HTMLElement | null = document.getElementById(htmlId) as HTMLElement;
// 	pdfDom.style.padding = '0 10px !important';
// 	const A4Width = 595.28;
// 	const A4Height = 841.89;
// 	const pageHeight = A4Height; // 设置每页高度
// 	let totalHeight = pdfDom.scrollHeight;
// 	let currentPosition = 0;
//
// 	let PDF = new jsPDF("p", "pt", "a4");
//
// 	while (currentPosition < totalHeight) {
// 		let canvas = await html2canvas(pdfDom, {
// 			scale: 2,
// 			useCORS: true,
// 			backgroundColor: bgColor,
// 			windowHeight: totalHeight, // 设置渲染窗口高度为整个页面高度
// 			y: currentPosition // 设置渲染起始位置
// 		});
//
// 		let imgData = canvas.toDataURL("image/jpeg", 1.0);
//
// 		if (currentPosition > 0) {
// 			PDF.addPage();
// 		}
//
// 		PDF.addImage(imgData, "JPEG", 0, 0, A4Width, (A4Width / canvas.width) * canvas.height);
// 		currentPosition += pageHeight;
// 		pdfDom.scrollTop = currentPosition; // 滚动到下一页开始的位置
// 		await new Promise(resolve => setTimeout(resolve, 100)); // 等待页面渲染
// 	}
//
// 	PDF.save(title + ".pdf");
// }

export const htmlToPDF = async (htmlId: string, title: string = "报表", bgColor = "#fff") => {
	let pdfDom: HTMLElement | null = document.getElementById(htmlId) as HTMLElement
	pdfDom.style.padding = '0 10px !important'
	const A4Width = 595.28;
	const A4Height = 841.89;
	let canvas = await html2canvas(pdfDom, {
		scale: 2,
		useCORS: true,
		backgroundColor: bgColor,
	});
	let pageHeight = (canvas.width / A4Width) * A4Height;
	let leftHeight = canvas.height;
	let position = 0;
	let imgWidth = A4Width;
	let imgHeight = (A4Width / canvas.width) * canvas.height;
	/*
	 根据自身业务需求  是否在此处键入下方水印代码
	*/
	let pageData = canvas.toDataURL("image/jpeg", 1.0);
	let PDF = new jsPDF("p", 'pt', 'a4');
	if (leftHeight < pageHeight) {
		PDF.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
	} else {
		while (leftHeight > 0) {
			PDF.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
			leftHeight -= pageHeight;
			position -= A4Height;
			if (leftHeight > 0) PDF.addPage();
		}
	}
	PDF.save(title + ".pdf");
}
